<?php
/**
 * Created by PhpStorm.
 * User: xiao
 * Date: 2017/6/16
 * Time: 下午4:12
 */

namespace app\src\sellerApply\logic;


use app\src\account\enmu\AccountEnmu;
use app\src\admin\api\UserApi;
use app\src\base\helper\ExceptionHelper;
use app\src\base\logic\BaseLogic;
use app\src\invite\logic\InviteCodeLogic;
use app\src\seller\helper\AddressHelper;
use app\src\seller\logic\SellerLogic;
use app\src\sellerApply\model\SellerApply;
use app\src\user\action\DeleteAction;
use app\src\user\action\RegisterAction;
use app\src\user\logic\UcenterMemberLogic;
use think\Db;
use think\exception\DbException;
use app\src\platform\logic\PlatformLogic;
class SellerApplyLogic extends BaseLogic
{
    protected function _init()
    {
        $this->setModel(new SellerApply());
    }

    /**
     * 添加商家申请
     * @param $parent_id
     * @param $entity
     * @return array
     */
    public function addApply($parent_id, $entity)
    {
        $data = [
            'parent_id' => $parent_id,
            'name' => $entity['name'],
            'price' => isset($entity['price']) ? $entity['price'] : 0,
            'position' => $entity['position'],
            'contact_number' => $entity['contact_number'],
            'logo' => $entity['logo'],
            'main_img' => $entity['main_img'],
            'main_img_small' => $entity['main_img_small'],
            'synopsis' => $entity['synopsis'],
            'scope' => $entity['scope'],
            'first_offer' => $entity['first_offer'],
            'first_offer_num' => $entity['first_offer_num'],
            'discount_rate' => $entity['discount_rate'],
            'rack_back_rate' => $entity['rack_back_rate'],
            'apply_info' => $entity['apply_info'],
            'bank_card_name' => isset($entity['bank_card_name']) ? $entity['bank_card_name'] : '',
            'bank_card_no' => isset($entity['bank_card_no']) ? $entity['bank_card_no'] : '',
            'apply_status' => 0,
            'create_time' => NOW_TIME,
            'update_time' => NOW_TIME,
            'status' => 0,
            'category_id' => isset($entity['category_id']) ? $entity['category_id'] : ''
        ];

        $result = $this->add($data);
        if($result['status']){
            return $this->apiReturnSuc('success');
        }else{
            return $this->apiReturnErr($result['info']);
        }
    }

    /**
     * 商家申请列表
     * @param array $page
     * @param int $apply_status
     * @return array
     */
    public function applyList($page = ['curpage'=>1,'size'=>10], $apply_status = 0)
    {
        $map = [
            'apply_status' => $apply_status,
            'status' => 0
        ];

        $order = ['create_time' => 'desc'];
        $result = $this->queryWithCount($map, $page, $order);

        return $result;
    }

    /**
     * 商家申请详情
     * @param $apply_id
     * @return array
     */
    public function applyDetail($apply_id)
    {
        try{
            $map = [
                'apply.id' => $apply_id,
                'apply.status' => 0
            ];

            $model = $this->getModel();
            $result = $model->alias('apply')->field('apply.*,plat2.name as parent_name')
                ->join('__PLATFORM__ plat2', 'apply.parent_id = plat2.id', 'LEFT')
                ->where($map)->find();

            if(empty($result)) return $this->apiReturnErr('error platform apply');

            return $this->apiReturnSuc($result);
        }catch (DbException $ex){
            return $this->apiReturnErr(ExceptionHelper::getErrorString($ex));
        }
    }


    /**
     * 通过或否决申请
     * @param $apply_idz
     * @param bool $pass
     * @return array
     */
    public function passApply($apply_id, $pass = true)
    {
        //申请中的才能通过
        $result = $this->getInfo(['id' => $apply_id, '	apply_status' => 0, 'status' => 0]);
        if(!$result['status']) return $this->apiReturnErr($result['info']);
        if(empty($result['info'])) return $this->apiReturnErr('error apply');
        $apply_info = $result['info'];
        $_apply = json_decode($apply_info['apply_info'], true);

        $apply_status = $pass ? 1 : 2;
        Db::startTrans();
        $result = $this->save(['id' => $apply_id], ['apply_status' =>  $apply_status, 'update_time' => NOW_TIME]);
        if($result['status']){
            if($pass){
                $account_mobile = $_apply['account_mobile'];
                $account_psw = $_apply['account_psw'];

                //判断该账号是否已注册，已注册则直接使用该账号
                $map = ['mobile' => $account_mobile, 'country_no' => '+86', 'status' => 1 ];
                $result = (new UcenterMemberLogic)->getInfo($map);
                if(!$result['status']) return $this->apiReturnErr($result['info']);
                if(!empty($result['info'])) {
                    $uid = $result['info']['id'];
                }else{
                    //创建账号
                    //创建账号
                    //查询父级平台邀请码
                    $result = (new InviteCodeLogic)->getInviteCode(AccountEnmu::PLATFORM, $apply_info['parent_id']);
                    if(!$result['status']){
                        Db::rollback();
                        return $this->apiReturnErr($result['info']);
                    }
                    $invite_code = $result['info']['invite_code'];
                    $result = (new RegisterAction)->registerProcess($account_mobile, $account_mobile, '+86',$account_psw, '', $invite_code);
                    if($result['status']){
                        $map = ['mobile' => $account_mobile, 'country_no' => '+86', 'status' => 1 ];
                        $result = (new UcenterMemberLogic)->getInfo($map);
                        if(!$result['status']) return $this->apiReturnErr($result['info']);
                        $uid = $result['info']['id'];
                    }else{
                        Db::rollback();
                        return $this->apiReturnErr($result['info']);
                    }
                }

                //根据商家地址获取经纬度

                $ret = AddressHelper::getAddressPos($apply_info['position']);
                if($ret['status'] == 1){
                    return $this->apiReturnErr('获取商家经纬度失败');
                }else{
                    $location = $ret['result']['location'];
                    $lng = $location['lng'];
                    $lat = $location['lat'];
                }

                //创建商家
                $entity = [
                    'uid' => $uid,
                    'name' => $apply_info['name'],
                    'price' => $apply_info['price'],
                    'position' => $apply_info['position'],
                    'lng' => $lng,
                    'lat' => $lat,
                    'parent_id' => $apply_info['parent_id'],
                    'logo' => $apply_info['logo'],
                    'main_img' => $apply_info['main_img'],
                    'main_img_small' => $apply_info['main_img_small'],
                    'contact_number' => $apply_info['contact_number'],
                    'synopsis' => $apply_info['synopsis'],
                    'scope' => $apply_info['scope'],
                    'first_offer' => $apply_info['first_offer'], //首次优惠政策5元 10元,
                    'first_offer_num' => $apply_info['first_offer_num'],
                    'discount_rate' => $apply_info['discount_rate'],
                    'rack_back_rate' => $apply_info['rack_back_rate'],
                    'bank_card_name' => $apply_info['bank_card_name'],
                    'bank_card_no' => $apply_info['bank_card_no'],
                    'grade' => 5,
                    'category_id' => $apply_info['category_id']
                ];

                $SellerLogic = new SellerLogic;
                $result = $SellerLogic->addSeller($entity);
                if(!$result['status']) {
                    Db::rollback();
                    (new DeleteAction)->delete($account_mobile);
                    Db::commit();
                    return $this->apiReturnErr($result['info']);
                }
                $result = (new PlatformLogic)->getInfo(['id'=>$apply_info['parent_id'], 'status' => 0]);
                if(!$result['status']){
                    Db::rollback();
                    return $this->apiReturnErr($result['info']);
                }
                $preferential_money = $result['info']['preferential_money'] - $apply_info['first_offer'] * $apply_info['first_offer_num'];
                if($preferential_money >= 0) {
                    $result = (new PlatformLogic)->saveByID($apply_info['parent_id'], ['preferential_money' => intval($preferential_money)]);
                    if (!$result['status']) {
                        Db::rollback();
                        return $this->apiReturnErr($result['info']);
                    }
                }else{
                    Db::rollback();
                    return $this->apiReturnErr('剩余优惠金额不足，添加失败！');
                }
            }
            Db::commit();

            return $this->apiReturnSuc('success');
        }else{
            Db::rollback();
            return $this->apiReturnErr($result['info']);
        }
    }
}